package com.SouthernWall_404.age_tool.common.world.block;

import com.SouthernWall_404.age_tool.common.Network.ModChannels;
import com.SouthernWall_404.age_tool.common.Network.Packets.C2S.HandShake.MimicBlockRequireHandShakePacket;
import com.SouthernWall_404.age_tool.common.Network.Packets.S2C.MimicBlockRespondS2CPacket;
import com.SouthernWall_404.age_tool.common.init.ModBlocks;
import com.SouthernWall_404.age_tool.common.init.ModItems;
import com.SouthernWall_404.age_tool.common.world.Entity.MimicBlockEntity;
import com.SouthernWall_404.age_tool.common.world.Entity.TriggerBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.gameevent.GameEventListener;
import net.minecraft.world.phys.BlockHitResult;
import org.jetbrains.annotations.Nullable;


public class AbstractMimicBlock extends HorizontalDirectionalBlock implements EntityBlock {


    public BlockState defaultBlock= Blocks.AIR.defaultBlockState();
    public AbstractMimicBlock(Properties properties) {
        super(properties
                .strength(2.0f)
                .noOcclusion()
                .dynamicShape());
        this.registerDefaultState(this.stateDefinition.any()
                .setValue(FACING, Direction.NORTH));
    }
    @Override
    public RenderShape getRenderShape(BlockState state) {
        return RenderShape.INVISIBLE; // 确保返回不可见
    }

    @Override
    public InteractionResult use(BlockState blockState, Level level, BlockPos blockPos, Player player, InteractionHand hand, BlockHitResult blockPlaceContext) {


        if (player.getItemInHand(InteractionHand.OFF_HAND).is(ModItems.SUITCASE.get()))
        {
            ItemStack itemStack=player.getItemInHand(hand);
            if(itemStack.getItem()instanceof BlockItem blockItem)
            {
                BlockEntity blockEntity=level.getBlockEntity(blockPos);
                if(blockEntity instanceof TriggerBlockEntity triggerBlockEntity)
                {
//                    player.sendSystemMessage(Component.literal(""+triggerBlockEntity.mimicBlock));
                    triggerBlockEntity.mimicBlock=blockItem.getBlock().getStateForPlacement(new BlockPlaceContext(player,hand,itemStack,blockPlaceContext));

//                    player.sendSystemMessage(Component.literal(""+triggerBlockEntity.mimicBlock));
                    if (level.isClientSide) {
                        player.swing(hand);
                    }

                    triggerBlockEntity.setChanged(); // 标记为已更改
                    return InteractionResult.sidedSuccess(level.isClientSide);
                }
            }
            else if(itemStack.isEmpty())
            {
                BlockEntity blockEntity=level.getBlockEntity(blockPos);
                if(blockEntity instanceof TriggerBlockEntity triggerBlockEntity)
                {
//                    player.sendSystemMessage(Component.literal(""+triggerBlockEntity.mimicBlock));
                    triggerBlockEntity.mimicBlock=defaultBlock;

                    triggerBlockEntity.setChanged(); // 标记为已更改
                    if (level.isClientSide) {
                        player.swing(hand);
                    }
                    return InteractionResult.sidedSuccess(level.isClientSide);
                }

            }


        }

        if (level.isClientSide) {
            player.swing(hand);
        }
        return InteractionResult.sidedSuccess(level.isClientSide);


//        return InteractionResult.FAIL;
//        return super.use(blockState, level, blockPos, player, hand, p_60508_);
    }

    private void syncMimicBlockToClients(ServerLevel level, BlockPos pos, CompoundTag mimicPack) {
        if (mimicPack == null) {
            // 如果 mimicPack 为空，创建一个默认的
            BlockEntity blockEntity = level.getBlockEntity(pos);
            if (blockEntity instanceof TriggerBlockEntity triggerBlockEntity) {
                triggerBlockEntity.saveBlock(); // 确保数据已保存
                mimicPack = triggerBlockEntity.mimicPack;
            }
        }

        if (mimicPack != null) {
            MimicBlockRespondS2CPacket packet = new MimicBlockRespondS2CPacket(mimicPack, pos);

            // 发送给所有正在追踪此区块的玩家
            for (ServerPlayer player : level.players()) {
                if (player.distanceToSqr(pos.getX(), pos.getY(), pos.getZ()) < 64 * 64) {
                    ModChannels.sendToClient(packet, player);
                }
            }
        }
    }

    @Override
    public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) {
        super.onPlace(state, level, pos, oldState, isMoving);
        if (!level.isClientSide) {
            BlockEntity blockEntity = level.getBlockEntity(pos);
            if (blockEntity instanceof TriggerBlockEntity triggerBlockEntity) {
                // 立即同步到所有客户端
                syncMimicBlockToClients((ServerLevel) level, pos, triggerBlockEntity.mimicPack);
            }
        }
    }

    @Override
    protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
        builder.add(FACING);
        super.createBlockStateDefinition(builder);
    }

    @Override
    public @Nullable BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) {
        return new MimicBlockEntity(blockPos,blockState);
    }



    @Override
    public @Nullable <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState blockState, BlockEntityType<T> p_153214_) {
        return (lvl, pos, st, blockEntity) -> {
                if(level.isClientSide)
                {
                    ModChannels.sendToServer(new MimicBlockRequireHandShakePacket(pos));
                }
        };
    }

    @Override
    public @Nullable <T extends BlockEntity> GameEventListener getListener(ServerLevel p_221121_, T p_221122_) {
        return EntityBlock.super.getListener(p_221121_, p_221122_);
    }
}
